//
//  RCCallSingleCallViewController.m
//  RongCallKit
//
//  Created by RongCloud on 16/3/21.
//  Copyright © 2016年 RongCloud. All rights reserved.
//

#import "RCCallSingleCallViewController.h"
#import "RCCXCall.h"
#import "RCCall.h"
#import "RCCallFloatingBoard.h"
#import "RCCallKitUtility.h"
#import "RCCallUserCallInfoModel.h"
#import "RCUserInfoCacheManager.h"
#import "RCloudImageView.h"
#import "XMCallRechargeView.h"

#import "XMGiftView.h"
#import "XMConversationInviteView.h"
#import "XMSVGAPlayView.h"
#import "XMSendInviteGiftView.h"
#import "XMRealTipView.h"
#import "XMCallNotEnoughView.h"
#import "XMCallDiscountTipView.h"

#import "XMInviteMessage.h"
#import "XMCustomSendMessage.h"

#import <RongIMLib/RongIMLib.h>
#import <RongCallLib/RongCallLib.h>
#import "RCCall.h"
#import "XMRCManager.h"

#import "XMGiftModel.h"
#import "XMBagModel.h"
#import "XMRTCConfigModel.h"
#import "XMRTCResultModel.h"
#import "XMRechargeViewController.h"


#define currentUserId ([RCIMClient sharedRCIMClient].currentUserInfo.userId)
@interface RCCallSingleCallViewController ()

@property (nonatomic, strong) RCUserInfo *remoteUserInfo;
@property (nonatomic, assign) BOOL isFullScreen;
@property (nonatomic, strong) XMUserModel *userModel;
@property (nonatomic, strong) XMCallRechargeView *reView;

@property (nonatomic, strong) XMGiftView *giftView;
@property (nonatomic, strong) XMSVGAPlayView *svgaPlayView;
@property (nonatomic, strong) XMConversationInviteView *inviteView;
@property (nonatomic, strong) UIButton *cardButton;
@property (nonatomic, strong) XMRTCConfigModel *rtcModel;
@property (nonatomic, assign) BOOL notEnough;
@property (nonatomic, strong) UILabel *notEnoughTipLa;

@property (nonatomic, strong) XMCallNotEnoughView *notEnoughView;
@property (nonatomic, strong) XMCallDiscountTipView *discountTipView;

@end

@implementation RCCallSingleCallViewController

// init
- (instancetype)initWithIncomingCall:(RCCallSession *)callSession {
    return [super initWithIncomingCall:callSession];
}

- (instancetype)initWithOutgoingCall:(NSString *)targetId mediaType:(RCCallMediaType)mediaType {
    if (targetId.length == 0) { NSAssert(NO, @"被叫端 id 不能为空"); return nil;}
    return [super initWithOutgoingCall:ConversationType_PRIVATE
                              targetId:targetId
                             mediaType:mediaType
                            userIdList:@[targetId]];
}

- (instancetype)initWithOutgoingCrossCall:(NSString *)targetId mediaType:(RCCallMediaType)mediaType {
    if (targetId.length == 0) { NSAssert(NO, @"被叫端 id 不能为空"); return nil;}
    return [super initWithOutgoingCrossCall:ConversationType_PRIVATE
                                   targetId:targetId
                                  mediaType:mediaType
                                 userIdList:@[targetId]];
}

- (instancetype)initWithActiveCall:(RCCallSession *)callSession {
    return [super initWithActiveCall:callSession];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onUserInfoUpdate:)
                                                 name:RCKitDispatchUserInfoUpdateNotification
                                               object:nil];
    
    RCUserInfo *userInfo = [[RCUserInfoCacheManager sharedManager] getUserInfo:self.callSession.targetId];
    if (!userInfo) {
        userInfo = [[RCUserInfo alloc] initWithUserId:self.callSession.targetId name:nil portrait:nil];
    }
    self.remoteUserInfo = userInfo;
    [self.remoteNameLabel setText:userInfo.name];
    [self.remotePortraitView setImageURL:[NSURL URLWithString:userInfo.portraitUri]];
    self.backgroundView.userInteractionEnabled = YES;
    [self.backgroundView
     addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
                                                                  action:@selector(backgroundSingleViewClicked)]];
    [self userObtain];
    [self giftData];
    [self bagData];
    [self rtcData];
    [self viewBlock];
    [self registerNotification];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self mineGolds];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.isFullScreen = NO;
    [RCCallKitUtility checkSystemPermission:self.callSession.mediaType
                                    success:^{} error:^{
        [self hangupButtonClicked];
    }];
}

#pragma mark - Actions
- (void)didTapGift {
    if (kUserModel.isMan) {
        self.giftView.isInvite = NO;
        [self xm_showGiftView];
    } else {
        if (self.userModel.invite_state) {
            self.giftView.isInvite = NO;
            [self xm_showGiftView];
        } else {
            [self showinviteViewType:self.mediaType == RCCallMediaAudio ? XMConversationInviteAudiolGift :XMConversationInviteVideoGift];
        }
    }
}

- (void)subVideoViewClicked {
    if ([self.remoteUserInfo.userId isEqualToString:self.callSession.targetId]) {
        RCUserInfo *userInfo = [RCIMClient sharedRCIMClient].currentUserInfo;
        
        self.remoteUserInfo = userInfo;
        [self.remoteNameLabel setText:userInfo.name];
        [self.remotePortraitView setImageURL:[NSURL URLWithString:userInfo.portraitUri]];
        
        [self.callSession setVideoView:self.mainVideoView userId:self.remoteUserInfo.userId];
        [self.callSession setVideoView:self.subVideoView userId:self.callSession.targetId];
    } else {
        RCUserInfo *userInfo = [[RCUserInfoCacheManager sharedManager] getUserInfo:self.callSession.targetId];
        if (!userInfo) {
            userInfo = [[RCUserInfo alloc] initWithUserId:self.callSession.targetId name:nil portrait:nil];
        }
        self.remoteUserInfo = userInfo;
        [self.remoteNameLabel setText:userInfo.name];
        [self.remotePortraitView setImageURL:[NSURL URLWithString:userInfo.portraitUri]];
        
        [self.callSession setVideoView:self.subVideoView userId:[RCIMClient sharedRCIMClient].currentUserInfo.userId];
        [self.callSession setVideoView:self.mainVideoView userId:self.remoteUserInfo.userId];
    }
}

- (void)didTapCameraCloseButton {
    [self resetLayout:self.callSession.isMultiCall mediaType:RCCallMediaAudio callStatus:self.callSession.callStatus];
}

- (RCCallUserCallInfoModel *)generateUserModel:(NSString *)userId {
    RCCallUserCallInfoModel *userModel = [[RCCallUserCallInfoModel alloc] init];
    userModel.userId = userId;
    userModel.userInfo = [[RCUserInfoCacheManager sharedManager] getUserInfo:userId];
    
    if ([userId isEqualToString:currentUserId]) {
        userModel.profile = self.callSession.myProfile;
    } else {
        for (RCCallUserProfile *userProfile in self.callSession.userProfileList) {
            if ([userProfile.userId isEqualToString:userId]) {
                userModel.profile = userProfile;
                break;
            }
        }
    }
    
    return userModel;
}

#pragma mark - resetLayout
- (void)resetLayout:(BOOL)isMultiCall mediaType:(RCCallMediaType)mediaType callStatus:(RCCallStatus)sessionCallStatus {
    [super resetLayout:isMultiCall mediaType:mediaType callStatus:sessionCallStatus];
    
    RCCallStatus callStatus = sessionCallStatus;
    if ((callStatus == RCCallIncoming || callStatus == RCCallRinging) &&
        [RCCXCall sharedInstance].acceptedFromCallKit) {
        callStatus = RCCallActive;
        [RCCXCall sharedInstance].acceptedFromCallKit = NO;
    }
    
    UIImage *remoteHeaderImage = self.remotePortraitView.image;
    
    [self.reView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(26);
        make.right.equalTo(self.view).offset(-18);
        make.top.equalTo(self.view).offset(kStatusBarHeight + 20);
        
    }];
    
    self.minimizeButton.hidden = YES;
    
#pragma mark - 语音通话
    if (mediaType == RCCallMediaAudio) {
        XMLog(@"mediaType-%ld", self.callSession.mediaType);
        
        self.giftButton.hidden = YES;
        _remotePortraitView.layer.cornerRadius = 45;
        
        [self.acceptButton setImage:[RCCallKitUtility imageFromVoIPBundle:@"voip/answer.png"]
                           forState:UIControlStateNormal];
        [self.acceptButton setImage:[RCCallKitUtility imageFromVoIPBundle:@"voip/answer_hover.png"]
                           forState:UIControlStateHighlighted];
        self.remotePortraitView.frame =
        CGRectMake((self.view.frame.size.width - RCCallHeaderLength) / 2,
                   RCCallTopGGradientHeight + RCCallStatusBarHeight, RCCallHeaderLength, RCCallHeaderLength);
        self.remotePortraitView.image = remoteHeaderImage;
        self.remotePortraitView.hidden = NO;
        self.remotePortraitBgView.image = remoteHeaderImage;
        
        self.remoteNameLabel.frame =
        CGRectMake((self.view.frame.size.width - RCCallNameLabelWidth) / 2,
                   RCCallTopGGradientHeight + RCCallHeaderLength + RCCallTopMargin + RCCallStatusBarHeight,
                   RCCallNameLabelWidth, RCCallMiniLabelHeight);
        self.remoteNameLabel.hidden = NO;
        
        self.remoteNameLabel.textAlignment = NSTextAlignmentCenter;
        self.tipsLabel.textAlignment = NSTextAlignmentCenter;
        
        self.statusView.frame = CGRectMake(0, 0, 17, 4);
        self.statusView.center = self.remotePortraitView.center;
        
        [self.giftButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(34);
            make.centerX.equalTo(self.hangupButton);
            make.bottom.equalTo(self.hangupButton.mas_top).offset(-30);
        }];
        
        
        [self.cardButton setImage:kGetImage(@"call_voicecard") forState:UIControlStateNormal];
        [self.cardButton setImagePosition:XMImagePositionLeft spacing:5];
        [self.cardButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.priceLabel);
            make.top.equalTo(self.priceLabel.mas_bottom).offset(8);
        }];
        
#pragma mark - 正在呼出
        if (callStatus == RCCallDialing) {
            self.remotePortraitView.alpha = 0.5;
            self.blurView.hidden = NO;
            self.statusView.hidden = NO;
            self.remotePortraitBgView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            self.remotePortraitBgView.hidden = NO;
#pragma mark - 收到一个通话呼入后，正在振铃  正在呼入
        } else if (callStatus == RCCallRinging || callStatus == RCCallIncoming) {
            self.blurView.hidden = NO;
            self.remotePortraitView.alpha = 0.5;
            self.statusView.hidden = NO;
            self.remotePortraitBgView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            self.remotePortraitView.image = remoteHeaderImage;
            self.remotePortraitBgView.hidden = NO;
#pragma mark - 正在通话
        } else if (callStatus == RCCallActive) {
            self.blurView.hidden = NO;
            self.remotePortraitView.alpha = 1.0;
            self.statusView.hidden = YES;
            self.remotePortraitBgView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            self.remotePortraitView.image = remoteHeaderImage;
            self.remotePortraitBgView.hidden = NO;
            self.remotePortraitBgView.image = remoteHeaderImage;
            
            self.minimizeButton.hidden = NO;
            self.giftButton.hidden = NO;
        } else {
            self.statusView.hidden = YES;
            self.remotePortraitView.alpha = 1.0;
            self.remotePortraitView.image = remoteHeaderImage;
            self.remotePortraitBgView.hidden = NO;
            self.cardButton.hidden = YES;
            self.priceLabel.hidden = YES;
        }
        
        if (callStatus != RCCallActive) {
            [self.priceLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.tipsLabel);
                make.top.equalTo(self.tipsLabel.mas_bottom).offset(8);
            }];
        } else {
            [self.priceLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.timeLabel.mas_bottom).offset(10);
                make.centerX.equalTo(self.timeLabel);
            }];
        }
        
        self.mainVideoView.hidden = YES;
        self.subVideoView.hidden = YES;
        [self resetRemoteUserInfoIfNeed];
    } else {
#pragma mark - 视频通话
        _remotePortraitView.layer.cornerRadius = 25;
        self.remotePortraitBgView.hidden = YES;
        
        [self.acceptButton setImage:[RCCallKitUtility imageFromVoIPBundle:@"voip/answervideo.png"]
                           forState:UIControlStateNormal];
        [self.acceptButton setImage:[RCCallKitUtility imageFromVoIPBundle:@"voip/answervideo_hover.png"]
                           forState:UIControlStateHighlighted];
        
        [self.cardButton setImage:kGetImage(@"call_videocard") forState:UIControlStateNormal];
        [self.cardButton setTitle:self.rtcModel.goods_title forState:UIControlStateNormal];
        [self.cardButton setImagePosition:XMImagePositionLeft spacing:5];
        
        if (callStatus == RCCallDialing) {
            self.mainVideoView.hidden = NO;
            //            self.mainVideoView.frame = CGRectMake(0, RCCallStatusBarHeight, self.view.frame.size.width, self.view.frame.size.height - RCCallExtraSpace - RCCallStatusBarHeight);
            [self.callSession setVideoView:self.mainVideoView userId:self.callSession.caller];
        } else if (callStatus == RCCallActive) {
            self.mainVideoView.hidden = NO;
            [self.callSession setVideoView:self.mainVideoView userId:self.callSession.targetId];
        } else if (callStatus == RCCallIncoming || callStatus == RCCallRinging) {
            self.mainVideoView.hidden = NO;
            [self.callSession setVideoView:self.mainVideoView userId:currentUserId];
        } else {
            self.mainVideoView.hidden = YES;
        }
        
        if (callStatus == RCCallActive) {
            self.minimizeButton.hidden = NO;
            self.remotePortraitBgView.hidden = YES;
            self.remotePortraitView.hidden = YES;
            self.remoteNameLabel.hidden = YES;
            [self.remoteNameLabel setText:self.remoteUserInfo.name];
            
            self.remoteNameLabel.hidden = NO;
            self.remoteNameLabel.textAlignment = NSTextAlignmentCenter;
            
        } else if (callStatus == RCCallDialing) {
            self.remotePortraitBgView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            self.remotePortraitView.image = remoteHeaderImage;
            self.remotePortraitView.hidden = NO;
            self.remoteNameLabel.hidden = NO;
            
            [self.remotePortraitBgView
             setImageURL:[NSURL URLWithString:[self generateUserModel:currentUserId].userInfo.portraitUri]];
            
            //            [self.remoteNameLabel setText:[self generateUserModel:currentUserId].userInfo.name];
            self.remoteNameLabel.hidden = NO;
            self.remoteNameLabel.textAlignment = NSTextAlignmentCenter;
        } else if (callStatus == RCCallIncoming || callStatus == RCCallRinging) {
            self.remotePortraitView.image = remoteHeaderImage;
            self.remotePortraitView.hidden = NO;
            
            //            self.remotePortraitBgView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            //            self.remotePortraitBgView.image = remoteHeaderImage;
            //            self.remotePortraitBgView.hidden = NO;
            
            self.remoteNameLabel.hidden = NO;
            self.remoteNameLabel.textAlignment = NSTextAlignmentCenter;
        } else {
            self.remotePortraitBgView.hidden = YES;
            self.cardButton.hidden = YES;
            self.priceLabel.hidden = YES;
        }
        
        if (callStatus == RCCallActive) {
            [self.callSession setVideoView:self.subVideoView
                                    userId:[RCIMClient sharedRCIMClient].currentUserInfo.userId];
            self.subVideoView.hidden = NO;
        }
        
        self.remoteNameLabel.textAlignment = NSTextAlignmentCenter;
        self.statusView.frame = CGRectMake((self.view.frame.size.width - 17) / 2,
                                           RCCallVerticalMargin * 3 + (RCCallHeaderLength - 4) / 2, 17, 4);
        
        if (callStatus == RCCallDialing) {
            self.statusView.hidden = YES;
            self.blurView.hidden = YES;
        } else if (callStatus == RCCallIncoming || callStatus == RCCallRinging) {
            self.remotePortraitView.alpha = 0.5;
            //            self.remotePortraitBgView.hidden = NO;
            self.statusView.hidden = YES;
            self.blurView.hidden = YES;
        } else {
            self.statusView.hidden = YES;
            self.blurView.hidden = YES;
            self.remotePortraitView.alpha = 1.0;
        }
        
        if (mediaType == RCCallMediaVideo) {
            [self.subVideoView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.view).offset(20);
                make.top.equalTo(self.minimizeButton.mas_bottom).offset(30);
                make.width.mas_equalTo(74);
                make.height.mas_offset(108);
            }];
            
            [self.remotePortraitView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.view).offset(20);
                make.top.equalTo(self.minimizeButton.mas_bottom).offset(30);
                make.width.mas_equalTo(50);
                make.height.mas_offset(50);
            }];
            
            [self.muteButton setImage:kGetImage(@"call_mute_n") forState:UIControlStateNormal];
            [self.muteButton setImage:kGetImage(@"call_mute_s") forState:UIControlStateSelected];
            [self.muteButton setImage:kGetImage(@"call_mute_s") forState:UIControlStateHighlighted];
            
            [self.muteButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(self.view).offset(-10);
                make.top.equalTo(self.reView.mas_bottom).offset(30);
                make.width.mas_equalTo(37);
                make.height.mas_offset(30);
            }];
            
            [self.closeCameraButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.muteButton);
                make.top.equalTo(self.muteButton.mas_bottom).offset(30);
                make.width.mas_equalTo(37);
                make.height.mas_offset(29);
            }];
            
            [self.cameraSwitchButton setImage:kGetImage(@"call_flip") forState:UIControlStateNormal];
            [self.cameraSwitchButton setImage:kGetImage(@"call_flip") forState:UIControlStateHighlighted];
            [self.cameraSwitchButton setImage:kGetImage(@"call_flip") forState:UIControlStateSelected];
            [self.cameraSwitchButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.muteButton);
                make.top.equalTo(self.closeCameraButton.mas_bottom).offset(30);
                make.width.mas_equalTo(37);
                make.height.mas_offset(29);
            }];
            
            [self.faceButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.muteButton);
                make.top.equalTo(self.cameraSwitchButton.mas_bottom).offset(30);
                make.width.mas_equalTo(37);
                make.height.mas_offset(29);
            }];
            
            [self.giftButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.muteButton);
                make.top.equalTo(self.faceButton.mas_bottom).offset(30);
                make.width.mas_equalTo(37);
                make.height.mas_offset(29);
            }];
            
            if (callStatus != RCCallActive) {
                [self.remoteNameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(self.remotePortraitView.mas_top).offset(0);
                    make.left.equalTo(self.remotePortraitView.mas_right).offset(12);
                }];
                
                [self.tipsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(self.remotePortraitView.mas_bottom).offset(0);
                    make.left.equalTo(self.remotePortraitView.mas_right).offset(12);
                }];
                
                [self.priceLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(self.tipsLabel.mas_bottom).offset(8);
                    make.left.equalTo(self.remotePortraitView.mas_right).offset(12);
                }];
            } else {
                [self.remoteNameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(self.reView.mas_bottom).offset(12);
                    make.centerX.equalTo(self.view);
                }];
                
                [self.tipsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.center.equalTo(self.view);
                }];
                
                if (![XMUtil isBlankString:self.rtcModel.goods_index]) {
                    [self.cardButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.right.equalTo(self.view.mas_centerX).offset(16);
                        make.top.equalTo(self.remoteNameLabel.mas_bottom).offset(8);
                    }];
                    
                    [self.timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(self.cardButton.mas_right);
                        make.centerY.equalTo(self.cardButton);
                    }];
                } else {
                    [self.timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(self.remoteNameLabel.mas_bottom).offset(8);
                        make.centerX.equalTo(self.view);
                    }];
                }
                
                [self.priceLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(self.timeLabel.mas_bottom).offset(8);
                    make.centerX.equalTo(self.view);
                }];
            }
        }
    }
    
    if (kUserModel.isMan && (self.callSession.callStatus == RCCallActive)) {
        self.cardButton.hidden = [XMUtil isBlankString:self.rtcModel.goods_index];
        [self.cardButton setTitle:self.rtcModel.goods_title forState:UIControlStateNormal];
    } else {
        self.cardButton.hidden = YES;
    }
    
    [self.notEnoughTipLa mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.priceLabel.mas_bottom).offset(8);
    }];
}

- (void)resetRemoteUserInfoIfNeed {
    if (![self.remoteUserInfo.userId isEqualToString:self.callSession.targetId]) {
        RCUserInfo *userInfo = [[RCUserInfoCacheManager sharedManager] getUserInfo:self.callSession.targetId];
        if (!userInfo) {
            userInfo = [[RCUserInfo alloc] initWithUserId:self.callSession.targetId name:nil portrait:nil];
        }
        self.remoteUserInfo = userInfo;
        [self.remoteNameLabel setText:userInfo.name];
        [self.remotePortraitView setImageURL:[NSURL URLWithString:userInfo.portraitUri]];
    }
}

- (BOOL)isSupportOrientation:(UIInterfaceOrientation)orientation {
    return [[UIApplication sharedApplication]
            supportedInterfaceOrientationsForWindow:[UIApplication sharedApplication].keyWindow] &
    (1 << orientation);
}

#pragma mark - UserInfo Update
- (void)onUserInfoUpdate:(NSNotification *)notification {
    NSDictionary *userInfoDic = notification.object;
    NSString *updateUserId = userInfoDic[@"userId"];
    RCUserInfo *updateUserInfo = userInfoDic[@"userInfo"];
    if ([updateUserId isEqualToString:self.remoteUserInfo.userId]) {
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.remoteUserInfo = updateUserInfo;
            [weakSelf.remoteNameLabel setText:updateUserInfo.name];
            [weakSelf.remotePortraitView setImageURL:[NSURL URLWithString:updateUserInfo.portraitUri]];
        });
    }
}

- (void)backgroundSingleViewClicked {
    if (self.callSession.mediaType == RCCallMediaVideo && self.callSession.callStatus == RCCallActive) {
        self.isFullScreen = !self.isFullScreen;
        [[UIApplication sharedApplication] setStatusBarHidden:self.isFullScreen];
        if (self.callSession.mediaType == RCCallMediaVideo && self.callSession.callStatus == RCCallActive) {
            self.minimizeButton.hidden = self.isFullScreen;
            self.handUpButton.hidden = self.isFullScreen;
            self.whiteBoardButton.hidden = self.isFullScreen;
            self.cameraSwitchButton.hidden = self.isFullScreen;
            self.addButton.hidden = self.isFullScreen;
            self.muteButton.hidden = self.isFullScreen;
            self.faceButton.hidden = self.isFullScreen;
            self.giftButton.hidden = self.isFullScreen;
            self.priceLabel.hidden = self.isFullScreen;
            self.closeCameraButton.hidden = self.isFullScreen;
            
            self.hangupButton.hidden = self.isFullScreen;
            //            self.cameraCloseButton.hidden = self.isFullScreen;
            self.remoteNameLabel.hidden = self.isFullScreen;
            self.timeLabel.hidden = self.isFullScreen;
            self.signalImageView.hidden = self.isFullScreen;
        }
    }
}

#pragma mark - Lazy
- (XMCallRechargeView *)reView {
    if (!_reView) {
        _reView = [XMCallRechargeView viewFromXib];
        [self.view addSubview:_reView];
    }
    return _reView;
}

- (RCloudImageView *)remotePortraitView {
    if (!_remotePortraitView) {
        _remotePortraitView = [[RCloudImageView alloc] init];
        [self.view addSubview:_remotePortraitView];
        _remotePortraitView.hidden = YES;
        [_remotePortraitView setPlaceholderImage:[RCCallKitUtility getDefaultPortraitImage]];
        _remotePortraitView.layer.masksToBounds = YES;
        if (RCKitConfigCenter.ui.globalConversationAvatarStyle == RC_USER_AVATAR_CYCLE &&
            RCKitConfigCenter.ui.globalMessageAvatarStyle == RC_USER_AVATAR_CYCLE) {
            //            _remotePortraitView.layer.cornerRadius = _remotePortraitView.size.width / 2;
            _remotePortraitView.layer.borderWidth = 1;
            _remotePortraitView.layer.borderColor = UIColor.whiteColor.CGColor;
            
        } else {
            _remotePortraitView.layer.cornerRadius = 4.f;
        }
    }
    return _remotePortraitView;
}

/// 大头像背景
- (RCloudImageView *)remotePortraitBgView {
    if (!_remotePortraitBgView) {
        _remotePortraitBgView = [[RCloudImageView alloc] init];
        
        [self.view insertSubview:_remotePortraitBgView aboveSubview:self.backgroundView];
        _remotePortraitBgView.hidden = YES;
        [_remotePortraitBgView setPlaceholderImage:[RCCallKitUtility getDefaultPortraitImage]];
        //        _remotePortraitBgView.layer.cornerRadius = 4;
        _remotePortraitBgView.layer.masksToBounds = YES;
        _remotePortraitBgView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _remotePortraitBgView;
}

- (UILabel *)remoteNameLabel {
    if (!_remoteNameLabel) {
        _remoteNameLabel = [[UILabel alloc] init];
        _remoteNameLabel.backgroundColor = [UIColor clearColor];
        _remoteNameLabel.textColor = [UIColor whiteColor];
        _remoteNameLabel.layer.shadowOpacity = 0.8;
        _remoteNameLabel.layer.shadowRadius = 3.0;
        _remoteNameLabel.layer.shadowColor = [UIColor blackColor].CGColor;
        _remoteNameLabel.layer.shadowOffset = CGSizeMake(0, 1);
        _remoteNameLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:21];
        _remoteNameLabel.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:_remoteNameLabel];
        _remoteNameLabel.hidden = YES;
    }
    return _remoteNameLabel;
}

- (UIImageView *)statusView {
    if (!_statusView) {
        _statusView = [[RCloudImageView alloc] init];
        [self.view addSubview:_statusView];
        _statusView.hidden = YES;
        _statusView.image = [RCCallKitUtility imageFromVoIPBundle:@"voip/voip_connecting"];
    }
    return _statusView;
}

- (UIView *)mainVideoView {
    if (!_mainVideoView) {
        _mainVideoView = [[UIView alloc] initWithFrame:self.backgroundView.frame];
        _mainVideoView.backgroundColor = RongVoIPUIColorFromRGB(0x262e42);
        
        [self.backgroundView addSubview:_mainVideoView];
        _mainVideoView.hidden = YES;
    }
    return _mainVideoView;
}

- (UIView *)subVideoView {
    if (!_subVideoView) {
        _subVideoView = [[UIView alloc] init];
        _subVideoView.backgroundColor = kHEX(@"#D8D8D8");
        kCornerRadius(_subVideoView, 8, 0, UIColor.clearColor);
        //        _subVideoView.layer.borderWidth = 1;
        //        _subVideoView.layer.borderColor = [[UIColor whiteColor] CGColor];
        
        [self.view addSubview:_subVideoView];
        _subVideoView.hidden = YES;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                              action:@selector(subVideoViewClicked)];
        [_subVideoView addGestureRecognizer:tap];
    }
    return _subVideoView;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - 新增

#pragma mark - initData
- (void)userObtain {
    if (self.targetId.length > 0) {
        NSMutableDictionary *dic = @{
            @"see_user_id": self.targetId,
            @"module": @"8"
        }.mutableCopy;
        [YHNetworkManager.sharedInstance postWithUrl:@"api/user/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
            if (tip.success) {
                XMUserModel *model = [XMUserModel mj_objectWithKeyValues:result];
                self.userModel = model;
                [self.remoteNameLabel setText:model.nickname];
                [self.remotePortraitView setImageURL:[NSURL URLWithString:model.avatar.file_url]];
                [[XMRCManager sharedInstance] updateUserCacheUserId:model.user_id alias:model.alias name:model.nickname portraitUri:model.avatar.file_url extra:[XMUtil extraJsonMember_time:model.member_time intimacy:model.intimacy]];
            }
        }];
    }
}

- (void)mineGolds {
    NSMutableDictionary *dic = @{
        @"module": @"4"
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            XMUserModel *model = [XMUserModel mj_objectWithKeyValues:result];
            kUserModel.golds = model.golds;
            self.userModel.invite_state = model.invite_state;
            [self.reView.goldButton setTitle:model.golds forState:UIControlStateNormal];
            [self compareBalance:kUserModel.golds.integerValue tip:NO];
        }
    }];
}

- (void)giftData {
    NSMutableDictionary *dic = @{
        @"module": @"1"
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/config/giftConfig" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, NSDictionary * _Nullable result) {
        if (tip.success) {
            self.giftView.giftArray = [XMGiftModel mj_objectArrayWithKeyValuesArray:[result objectForKey:@"record"]];
        }
    }];
    
    NSMutableDictionary *dic2 = @{
        @"module": @"2"
    }.mutableCopy;
    
    [YHNetworkManager.sharedInstance postWithUrl:@"api/config/giftConfig" parameters:dic2 completeBlock:^(XMResponseTip * _Nonnull tip, NSDictionary * _Nullable result) {
        if (tip.success) {
            self.giftView.memberArray = [XMGiftModel mj_objectArrayWithKeyValuesArray:[result objectForKey:@"record"]];
        }
    }];
}

- (void)bagData {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/chat/knapsack/list" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            NSArray <XMBagModel *> *array = [XMBagModel mj_objectArrayWithKeyValuesArray:result[@"record"]];
            self.giftView.bagArray = array;
        }
    }];
}

#pragma mark - 送礼物
- (void)sendGift:(NSString *)gift_id
    animationUrl:(NSString *)animationUrl
      messageUid:(NSString *)messageUid {
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{
        @"gift_id": gift_id,
        @"target_user_id": self.targetId
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/chat/send/gift" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            XMGiftModel *giftModel = [XMGiftModel mj_objectWithKeyValues:result];
            if (tip.success) {
                XMWeakSelf(self);
                if ([GKCover hasCover]) {
                    [GKCover hideCoverWithHideBlock:^{
                        XMStrongSelf(self);
                        kUserModel.golds = giftModel.user_golds;
                        [self.reView.goldButton setTitle:giftModel.user_golds forState:UIControlStateNormal];
                        [self sendGiftMessage:giftModel];
                        [self.reView.goldButton setTitle:kUserModel.golds forState:UIControlStateNormal];
                        [self compareBalance:kUserModel.golds.integerValue tip:NO];
                        if (!self.userModel.is_hidden && ![XMUtil isBlankString:animationUrl]) {
                            [self showGiftSvgaPlayView:animationUrl finishBlock:^(SVGAPlayer *player) {
                                [GKCover hideCover];
                            }];
                        }
                    }];
                } else {
                    kUserModel.golds = giftModel.user_golds;
                    [self.reView.goldButton setTitle:giftModel.user_golds forState:UIControlStateNormal];
                    [self sendGiftMessage:giftModel];
                    [self.reView.goldButton setTitle:kUserModel.golds forState:UIControlStateNormal];
                    [self compareBalance:kUserModel.golds.integerValue tip:NO];
                    if (!self.userModel.is_hidden && ![XMUtil isBlankString:animationUrl]) {
                        [self showGiftSvgaPlayView:animationUrl finishBlock:^(SVGAPlayer *player) {
                            [GKCover hideCover];
                        }];
                    }
                }
                if (messageUid.length > 0) {
                    [[RCCoreClient sharedCoreClient] updateMessageExpansion:@{@"status": @"1"} messageUId:messageUid success:^{
                        // 更新发起者在这里处理更新扩展后的 UI 数据刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [kNotificationCenter postNotificationName:@"callreload" object:messageUid];
                        });
                    } error:^(RCErrorCode status) {
                        
                    }];
                }
            }
        }
    }];
}

- (void)sendGiftMessage:(XMGiftModel *)model {
    XMCustomSendMessage *message = [XMCustomSendMessage giftMessageWithName:model.name golds:model.golds score:model.give_score.stringValue msgType:@(1) number:@(1) isVideo:@(1) index:model.index animUrl:model.animation.file_url imgUrl:model.image.file_url];
    
    [[RCIM sharedRCIM] sendMessage:ConversationType_PRIVATE
                          targetId:self.targetId
                           content:message
                       pushContent:nil
                          pushData:nil
                           success:^(long messageId) {
        
    }
                             error:^(RCErrorCode nErrorCode, long messageId){}];
}


- (void)sendGiftInviteMessage:(XMGiftModel *)model {
    XMInviteMessage *message = [XMInviteMessage giftMessageWithName:model.name golds:model.golds score:model.give_score.stringValue msgType:@(1) number:@(1) isVideo:@(1) index:model.index animUrl:model.animation.file_url imgUrl:model.image.file_url];
    [[RCIM sharedRCIM] sendMessage:ConversationType_PRIVATE
                          targetId:self.targetId
                           content:message
                       pushContent:nil
                          pushData:nil
                           success:^(long messageId) {
    }
                             error:^(RCErrorCode nErrorCode, long messageId){}];
}

///
/// - Parameters:
///   - type: 用户聊天类型 1 视频聊天 2 语音聊天
///   - status: 聊天状态标识 1 正常通话 2 已取消 3 已拒绝 4 未接通
///   - is_call: 是否为发起人 1 发起人 2 接收人
///   - room_id: 聊天房间标识
///   - handle_time: 会话开启时间（毫秒）
///   - target_user_id: 目标用户标识
///   - session_id: 聊天会话标识
///   - goods_index: 聊天会话标识
///   - completeBlock: 完成
///
- (void)callStartType:(NSNumber *)type
               status:(NSNumber *)status
              is_call:(NSNumber *)is_call
              room_id:(NSString *)room_id
          handle_time:(NSNumber *)handle_time
       target_user_id:(NSString *)target_user_id
           session_id:(NSString *)session_id
          goods_index:(NSString *)goods_index
        completeBlock:(YHCompleteBlock)completeBlock {
    NSMutableDictionary *paramDic = @{
        @"type": type,
        @"status": status,
        @"is_call": is_call,
        @"room_id": [NSString xm_stringNoNullWith:room_id],
        @"handle_time": handle_time,
        @"target_user_id": [NSString xm_stringNoNullWith:target_user_id],
        @"session_id": [NSString xm_stringNoNullWith:session_id],
    }.mutableCopy;
    
    if (goods_index.length > 0) {
        [paramDic setObject:goods_index forKey:@"goods_index"];
    }
    
    [[YHNetworkManager sharedInstance] postWithUrl:@"api/chat/rtc/start"
                                        parameters:paramDic
                                     completeBlock:^(XMResponseTip *_Nonnull tip, id _Nullable result) {
        if (tip.success) {
            XMRTCResultModel *model = [XMRTCResultModel mj_objectWithKeyValues:result];
            self.rtcModel.goods_title = model.goods_title;
            [self.cardButton setTitle:model.goods_title forState:UIControlStateNormal];
            [self setupPrice:model.consume_golds];
            if (model.chat_state == 0) {
                [self hangupButtonClicked];
            }
        } else {
            [self hangupButtonClicked];
        }
        completeBlock(tip, result);
    }];
}

#pragma mark - super
- (void)acceptButtonClicked {
    if (![self checkBalanceEnough:self.mediaType == RCCallMediaAudio ? @(self.rtcModel.voice_golds) : @(self.rtcModel.video_golds) message:self.mediaType == RCCallMediaAudio ? kStringFormat(@"语音通话%@金币/分钟", @(self.rtcModel.voice_golds)) : kStringFormat(@"对方设置视频通话为%@金币/分钟", @(self.rtcModel.video_golds)) isGift:NO]) {
        return;
    }
    [super acceptButtonClicked];
}

- (void)callWillConnect {
    if (self.mediaType == RCCallMediaVideo) {
        [self.remoteNameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.reView.mas_bottom).offset(12);
            make.centerX.equalTo(self.view);
        }];
        
        [self.tipsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.view);
        }];
        
        if (![XMUtil isBlankString:self.rtcModel.goods_index]) {
            [self.cardButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(self.view.mas_centerX).offset(16);
                make.top.equalTo(self.remoteNameLabel.mas_bottom).offset(8);
            }];
            
            [self.timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.cardButton.mas_right);
                make.centerY.equalTo(self.cardButton);
            }];
        } else {
            [self.timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.remoteNameLabel.mas_bottom).offset(8);
                make.centerX.equalTo(self.view);
            }];
        }
        
        [self.priceLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.timeLabel.mas_bottom).offset(8);
            make.centerX.equalTo(self.view);
        }];
    }
    
    [self callStartType:self.callSession.mediaType == RCCallMediaVideo ? @(1) : @(2) status:@(0) is_call:[self.callSession.caller isEqualToString:kUserModel.user_id] ? @(1) : @(2) room_id:self.callSession.callId handle_time:@(self.callSession.startTime) target_user_id:self.targetId session_id:self.callSession.sessionId goods_index:self.rtcModel.goods_index completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        
    }];
}

- (void)callWillDisconnect {
    if ([self.callSession.caller isEqualToString:kUserModel.user_id]) {
        [self callStartType:self.callSession.mediaType == RCCallMediaVideo ? @(1) : @(2) status:@(self.callSession.disconnectReason) is_call:[self.callSession.caller isEqualToString:kUserModel.user_id] ? @(1) : @(2) room_id:self.callSession.callId handle_time:@(self.callSession.startTime) target_user_id:self.targetId session_id:self.callSession.sessionId goods_index:@"" completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        }];
    }
}

- (void)callHandleSeconds:(NSNumber *)seconds {
    NSMutableDictionary *paramDic = @{
        @"seconds": seconds,
        @"session_id": [NSString xm_stringNoNullWith:self.callSession.sessionId]
    }.mutableCopy;
    [[YHNetworkManager sharedInstance] postWithUrl:@"api/chat/rtc/handle"
                                        parameters:paramDic
                                     completeBlock:^(XMResponseTip *_Nonnull tip, id _Nullable result) {
        
        if (tip.success) {
            XMRTCResultModel *model = [XMRTCResultModel mj_objectWithKeyValues:result];
            kUserModel.golds = kStringFormat(@"%ld", model.user_golds);
            [self.reView.goldButton setTitle:kUserModel.golds forState:UIControlStateNormal];
            [self compareBalance:kUserModel.golds.integerValue tip:NO];
        }
        
    }];
}

- (void)updateTalkTime:(long)second {
    if (!kUserModel.isMan) {
        return;
    }
    if (second % 60 == 0 && second > 0) {
        [self callHandleSeconds:@(second)];
    }
    if (second == 1) {
        [self mineGolds];
    }
    
    if (self.notEnough) {
        if (second % 60 >= 30) {
            self.notEnoughView.hidden = NO;
            self.notEnoughTipLa.hidden = NO;
            self.notEnoughTipLa.text = kStringFormat(@"通话剩余%ld秒", (60 - second % 60));
        }
    }
}

- (void)compareBalance:(NSInteger)balance tip:(BOOL)tip {
    if (!kUserModel.isMan) {
        return;
    }
    NSInteger gold = self.mediaType == RCCallMediaAudio ? self.rtcModel.voice_golds : self.rtcModel.video_golds;
    if (balance < gold) {
        if (tip) {
            [MBProgressHUD showHUDMsg:@"剩余金币即将不足，请充值" toView:self.view];
        }
        self.notEnough = YES;
    }
}

#pragma mark - viewBlock
- (void)viewBlock {
#pragma mark - 礼物
    XMWeakSelf(self);
    self.giftView.sendBlock = ^(XMGiftModel * _Nonnull model, BOOL isMember, BOOL isInvite) {
        XMStrongSelf(self);
        if (isInvite) {
            XMWeakSelf(self);
            [GKCover hideCoverWithHideBlock:^{
                XMStrongSelf(self);
                [self sendGiftInviteMessage:model];
            }];
            
        } else {
            if (![self checkBalanceEnough:model.golds message:kGlobalVariables.appConfig.chat.otherMsgTipStr isGift:YES]) {
                return;
            }
            [self sendGift:kStringFormat(@"%@", model.index) animationUrl:model.animation.file_url messageUid:@""];
        }
    };
    
    
    self.notEnoughView.reBlock = ^{
        XMStrongSelf(self);
        [self minimizeButtonClicked];
        [self toRecharge];
    };
    
    self.notEnoughView.closeBlock = ^{
        XMStrongSelf(self);
        self.notEnoughView.hidden = YES;
    };
    
    self.discountTipView.leftBlock = ^{
        XMStrongSelf(self);
        self.rtcModel.goods_index = @"";
        [GKCover hideCover];
    };
    
    self.discountTipView.rightBlock = ^{
        [GKCover hideCover];
        
    };
    
}

- (BOOL)checkBalanceEnough:(NSNumber *)price
                   message:(NSString *)message
                    isGift:(BOOL)isGift {
    if (isGift) {
        if (kUserModel.golds.integerValue < price.integerValue) {
            [MBProgressHUD showHUDMsg:message toView:nil completionBlock:^{
                [self minimizeButtonClicked];
                [self toRecharge];
            }];
            
            return NO;
        }
    } else {
        if (kUserModel.golds.integerValue < price.integerValue && kUserModel.isMan) {
            [MBProgressHUD showHUDMsg:message toView:nil completionBlock:^{
                [self minimizeButtonClicked];
                [self toRecharge];
            }];
            return NO;
        }
    }
    return YES;
}

- (void)toRecharge {
    XMRechargeViewController *vc = [[XMRechargeViewController alloc] initWithNibName:kStringFromClass(XMRechargeViewController) bundle:nil];
    [[UIViewController currentNavigatonController] pushViewController:vc animated:YES];
}

#pragma mark - 收到消息
- (void)didReceiveMessage:(RCMessage *)message leftDic:(NSDictionary *)leftDic {
    //    NSLog(@"收到消息:%@", message.mj_keyValues);
    if ([[XMCustomSendMessage getObjectName] isEqualToString:message.objectName] &&
        [message.content isKindOfClass:[XMCustomSendMessage class]] && !message.isOffLine) {
        XMCustomSendMessage *msg = (XMCustomSendMessage *)message.content;
        if (msg.isVideo.intValue != 0 && [msg.animUrl containsString:@"svga"]) {
            [self showGiftSvgaPlayView:msg.animUrl finishBlock:^(SVGAPlayer *player) {
                [GKCover hideCover];
            }];
        }
    }
    [self userObtain];
}

#pragma mark - 发送消息完成的回调 发送状态，0表示成功，非0表示失败
- (void)didSendMessageModel:(NSInteger)status model:(RCMessageModel *)messageModel {
    if (status == 0) {
        [self userObtain];
        if (self.userModel.is_hidden) {
            dispatch_async(dispatch_get_main_queue(), ^{
            });
        }
    }
}

- (XMGiftView *)giftView {
    if (_giftView == nil) {
        _giftView = [XMGiftView viewFromXib];
        _giftView.size = CGSizeMake(kScreenWidth, 382 + kBottomSafeHeight);
    }
    return _giftView;
}

- (void)xm_showGiftView {
    [self bagData];
    [self.giftView reloadGolod];
    [self.giftView resetViews];
    [GKCover coverFrom:self.view contentView:self.giftView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleBottom) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:NO];
}

- (XMConversationInviteView *)inviteView {
    if (!_inviteView) {
        _inviteView = [XMConversationInviteView viewFromXib];
        _inviteView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _inviteView;
}

#pragma mark - 各种邀请弹窗
- (void)showinviteViewType:(XMConversationInviteType)type {
    XMWeakSelf(self);
    [self.inviteView setupWithType:type sendBlock:^(XMConversationInviteType type) {
        XMStrongSelf(self);
        XMWeakSelf(self);
        [GKCover hideCoverWithHideBlock:^{
            XMStrongSelf(self);
            switch (type) {
                case XMConversationInviteAudiolGift:
                case XMConversationInviteVideoGift:
                    self.giftView.isInvite = NO;
                    [self xm_showGiftView];
                    break;
                default:
                    break;
            }
        }];
        
    } inviteBlock:^(XMConversationInviteType type) {
        XMStrongSelf(self);
        XMWeakSelf(self);
        [GKCover hideCoverWithHideBlock:^{
            XMStrongSelf(self);
            switch (type) {
                case XMConversationInviteAudiolGift:
                case XMConversationInviteVideoGift:
                    self.giftView.isInvite = YES;
                    [self xm_showGiftView];
                    break;
                default:
                    break;
            }
        }];
    }];
    
    [GKCover coverFrom:self.view contentView:self.inviteView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleBottom) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:NO];
}

- (XMSVGAPlayView *)svgaPlayView {
    if (_svgaPlayView == nil) {
        _svgaPlayView = [[XMSVGAPlayView alloc] initWithFrame:UIScreen.mainScreen.bounds];
    }
    return _svgaPlayView;
}

- (void)showGiftSvgaPlayView:(NSString *)urlStr
                 finishBlock:(void (^)(SVGAPlayer *player))finishBlock {
    if ([GKCover hasCover]) {
        [GKCover hideCoverWithHideBlock:^{
            [self showSvgaPlayView:urlStr finishBlock:^(SVGAPlayer *player) {
                finishBlock(player);
            }];
        }];
    } else {
        [self showSvgaPlayView:urlStr finishBlock:^(SVGAPlayer *player) {
            finishBlock(player);
        }];
    }
}

- (void)showSvgaPlayView:(NSString *)urlStr
             finishBlock:(void (^)(SVGAPlayer *player))finishBlock {
    [self.svgaPlayView playWithSource:urlStr
                          finishBlock:^(SVGAPlayer *_Nonnull player) {
        finishBlock(player);
    } faileBlock:^(NSError *_Nullable error) {
        [GKCover hideCover];
    }];
    [GKCover coverFrom:kWindow contentView:self.svgaPlayView style:GKCoverStyleTransparent showStyle:GKCoverShowStyleCenter showAnimStyle:GKCoverShowAnimStyleNone hideAnimStyle:GKCoverHideAnimStyleNone notClick:YES];
}

- (void)registerNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveMessageNotification:)
                                                 name:RCKitDispatchMessageNotification
                                               object:nil];
}

- (void)didReceiveMessageNotification:(NSNotification *)notification {
    RCMessage *message = notification.object;
    if ([[XMCustomSendMessage getObjectName] isEqualToString:message.objectName] &&
        [message.content isKindOfClass:[XMCustomSendMessage class]] && !message.isOffLine) {
        XMCustomSendMessage *msg = (XMCustomSendMessage *)message.content;
        if (msg.isVideo.intValue == 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showGiftSvgaPlayView:msg.animUrl finishBlock:^(SVGAPlayer *player) {
                    [GKCover hideCover];
                }];
            });
        }
        [self userObtain];
        [self mineGolds];
    }
    if ([[XMInviteMessage getObjectName] isEqualToString:message.objectName] &&
        [message.content isKindOfClass:[XMInviteMessage class]] && !message.isOffLine) {
        XMInviteMessage *msg = (XMInviteMessage *)message.content;
        if (msg.isVideo.intValue == 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                XMSendInviteGiftView *view = [XMSendInviteGiftView viewFromXib];
                view.message = msg;
                view.frame = kFRAME(0, 0, kScreenWidth, kScreenHeight);
                [self.view addSubview:view];
                
                XMWeakSelf(self);
                view.sendBlock = ^(XMSendInviteGiftView * _Nonnull view, XMInviteMessage * _Nonnull inviteMsg) {
                    XMStrongSelf(self);
                    if (![self checkBalanceEnough:inviteMsg.golds message:kGlobalVariables.appConfig.chat.otherMsgTipStr isGift:YES]) {
                        return;
                    }
                    [view removeFromSuperview];
                    [self sendGift:inviteMsg.index.stringValue animationUrl:inviteMsg.animUrl messageUid:message.messageUId];
                };
                
            });
        }
    }
    if ([message.objectName isEqualToString:@"RC:TxtMsg"]) {
        RCTextMessage *msg = (RCTextMessage *)message.content;
        if ([msg.content containsString:@"系统检测到您的视频有违规内容，请注意您的言行！"]) {
            [self.callSession setCameraEnabled:NO];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)([XMGlobalVariables sharedInstance].appConfig.chat.violation_time.intValue * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.callSession setCameraEnabled:YES];
            });
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if ([GKCover hasCover]) {
        [GKCover hideCover];
    }
}

- (UIButton *)cardButton {
    if (_cardButton == nil) {
        _cardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cardButton.adjustsImageWhenHighlighted = NO;
        [_cardButton setTitleColor:kHEX(@"#FFAE00") forState:UIControlStateNormal];
        _cardButton.titleLabel.font = kUIFont(12);
        [self.view addSubview:_cardButton];
        _cardButton.hidden = YES;
    }
    return _cardButton;
}

- (void)rtcData {
    NSMutableDictionary *dic = @{
        @"type": self.mediaType == RCCallMediaVideo ? @"1" : @"2",
        @"target_user_id": self.targetId,
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/chat/rtc/data" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            self.rtcModel = [XMRTCConfigModel mj_objectWithKeyValues:result];
            if (kUserModel.isMan && (self.callSession.callStatus == RCCallActive)) {
                [self.cardButton setTitle:self.rtcModel.goods_title forState:UIControlStateNormal];
                self.cardButton.hidden = [XMUtil isBlankString:self.rtcModel.goods_index];
            } else {
                self.cardButton.hidden = YES;
            }
            [self setupPrice:self.mediaType == RCCallMediaVideo ? self.rtcModel.video_golds : self.rtcModel.voice_golds];
            
            if (![XMUtil isBlankString:self.rtcModel.goods_index]) {
                if ([self.callSession.caller isEqualToString:kUserModel.user_id] && kUserModel.isMan) {
                    [MBProgressHUD createHudWithMsg:kStringFormat(@"%@接通后自动使用", self.rtcModel.goods_title) delay:3.0 toView:self.view icon:nil completionBlock:nil];
                } else {
                    if (kUserModel.isMan) {
                        self.discountTipView.discount = self.rtcModel.goods_title;
                        [self showDiscountTipView];
                    }
                }
            };
        }
    }];
}

- (void)setupPrice:(NSInteger)price {
    if (self.mediaType == RCCallMediaAudio) {
        self.priceLabel.text = kStringFormat(@"%ld金币/分钟", price);
    } else if (self.mediaType == RCCallMediaVideo) {
        if (kUserModel.isMan && price > [XMGlobalVariables sharedInstance].appConfig.chat.rtc_video_golds.intValue) {
            self.priceLabel.text = kStringFormat(@"对方设置%ld金币/分钟", price);
        } else {
            self.priceLabel.text = kStringFormat(@"%ld金币/分钟", price);
        }
    }
}

- (XMCallNotEnoughView *)notEnoughView {
    if (!_notEnoughView) {
        _notEnoughView = [XMCallNotEnoughView viewFromXib];
        _notEnoughView.size = CGSizeMake(kScreenWidth, kScreenHeight);
        _notEnoughView.hidden = YES;
        [self.view addSubview:_notEnoughView];
    }
    return _notEnoughView;
}

- (XMCallDiscountTipView *)discountTipView {
    if (!_discountTipView) {
        _discountTipView = [XMCallDiscountTipView viewFromXib];
        _discountTipView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _discountTipView;
}

- (void)showDiscountTipView {
    if (![self checkBalanceEnough:self.mediaType == RCCallMediaAudio ? @(self.rtcModel.voice_golds) : @(self.rtcModel.video_golds) message:self.mediaType == RCCallMediaAudio ? kStringFormat(@"语音通话%@金币/分钟", @(self.rtcModel.voice_golds)) : kStringFormat(@"对方设置视频通话为%@金币/分钟", @(self.rtcModel.video_golds)) isGift:NO]) {
        return;
    }
    
    if ([GKCover hasCover]) {
        [GKCover hideCoverWithHideBlock:^{
            [GKCover coverFrom:self.view contentView:self.discountTipView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
        }];
    } else {
        [GKCover coverFrom:self.view contentView:self.discountTipView style:GKCoverStyleTranslucent showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
    }
}

- (UILabel *)notEnoughTipLa {
    if (_notEnoughTipLa == nil) {
        _notEnoughTipLa = [[UILabel alloc] init];
        _notEnoughTipLa.textColor = UIColor.redColor;
        _notEnoughTipLa.font = kUIFont(16);
        _notEnoughTipLa.textAlignment = NSTextAlignmentCenter;
        _notEnoughTipLa.hidden = YES;
        [self.view addSubview:_notEnoughTipLa];
    }
    return _notEnoughTipLa;
}

@end
